package com.aurora.app.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.aurora.app.entity.CategoryThing;
import com.aurora.app.entity.CollectionThing;
import com.aurora.app.entity.ThingComment;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingImage;
import com.aurora.app.entity.User;
import com.aurora.app.enums.Level;
import com.aurora.app.enums.UtTsType;
import com.aurora.app.exption.NullEntityException;
import com.aurora.app.service.CategoryThingService;
import com.aurora.app.service.CollectionThingService;
import com.aurora.app.service.ThingCommentService;
import com.aurora.app.service.ThingImageService;
import com.aurora.app.service.ThingService;
import com.aurora.app.service.UserService;
import com.aurora.app.util.DateUtils;
import com.aurora.app.util.StandardResponseBody;
import com.aurora.app.util.WhichLevel;
import com.aurora.base.dto.QueryResult;

/**
 * 首页 闲置
 * 
 * @author yongjiang.lin
 *
 */
@Controller
@RequestMapping(value = "api/index")
public class IndexContoller {

	@Resource
	private CategoryThingService categoryThingService;
	@Resource
	private ThingService thingService;
	@Resource
	private ThingImageService thingImageService;
	@Resource
	private ThingCommentService commentService;
	@Resource
	private CollectionThingService collectionThingService;
	@Resource
	private UserService userService;

	/**
	 * 首页
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping()
	public ModelAndView index(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("index/index");
		List<CategoryThing> listCategoryThing = this.categoryThingService.all();
		mv.addObject("listCategoryThing", listCategoryThing);
		return mv;
	}

	/**
	 * 搜索页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "search",method = RequestMethod.GET)
	public ModelAndView search(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("index/search");
		mv.addObject("searchKey", request.getParameter("searchKey"));
		mv.addObject("catagoryId", request.getParameter("catagoryId"));
		return mv;
	}

	/**
	 * 闲置物品内容
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "thing")
	public ModelAndView thing(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("index/index_thing");

		List<Thing> list = this.thingService.getListWithPages(request);

		List<String> time = new ArrayList<String>();
		List<Long> commentNum = new ArrayList<Long>();
		// 等级
		List<String> llist = new ArrayList<String>();
		if (!CollectionUtils.isEmpty(list)) {
			for (Thing thing : list) {
				time.add(DateUtils.getMyFormatTime(thing.getCreateTime()));
				commentNum.add(this.commentService.getCommentNum(thing));
				llist.add(WhichLevel.getLevel(thing.getUser().getHuoyueIntegral(), thing.getUser().getJiaoyiIntegral())
						.ordinal() + "");
			}
		}

		mv.addObject("list", list);
		mv.addObject("commentNum", commentNum);
		mv.addObject("time", time);
		mv.addObject("llist", llist);
		return mv;
	}

	/**
	 * 获取物品详细信息
	 * 
	 * @param request
	 * @param thingId
	 * @return
	 */
	@RequestMapping(value = "goodsDetail")
	public ModelAndView goodsDetail(HttpServletRequest request, @RequestParam("THING_ID") String thingId) {
		ModelAndView mv = new ModelAndView("index/goods-detail");
		Thing thing = this.thingService.get(thingId);
		if (thing == null) {
			throw new NullEntityException("无法获取物品信息");
		}
		List<ThingImage> thingImageList = thing.getImages();
		String time = DateUtils.getMyFormatTime(thing.getCreateTime());
		User user = thing.getUser();
		Level level = WhichLevel.getLevel(user.getHuoyueIntegral(), user.getJiaoyiIntegral());

		long commentNum = this.commentService.getCommentNum(thing);
		long collectionNum = this.collectionThingService.getCollectionNum(thing);
		// 获取前5条收藏
		List<CollectionThing> collectionUserList = this.collectionThingService.getCollectionUser(thing, 0, 5);
		// 是否收藏
		User userLook = (User) request.getSession().getAttribute("user");
		boolean isCollection = this.collectionThingService.isCollection(userLook, thing);
		mv.addObject("commentNum", commentNum);
		mv.addObject("collectionNum", collectionNum);
		mv.addObject("collectionUserList", collectionUserList);
		mv.addObject("isCollection", isCollection);
		mv.addObject("sessionUser", userLook);
		mv.addObject("thing", thing);
		mv.addObject("time", time);
		mv.addObject("user", user);
		mv.addObject("level", level.ordinal());
		mv.addObject("thingImageList", thingImageList);
		return mv;
	}

	/**
	 * 闲置的搜索
	 * @param request
	 * @param pageNum
	 * @param pageSize
	 * @param searchKey
	 * @param catagoryId
	 * @return
	 */
	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "search",method = RequestMethod.POST)
	@ResponseBody
	public String search(HttpServletRequest request, int pageNum, int pageSize, String searchKey, String catagoryId) {
		CategoryThing catagory = null;
		if (StringUtils.isNotBlank(catagoryId)) {
			catagory = this.categoryThingService.get(catagoryId);
		}
		List<Thing> tList = this.thingService.searchListWithPages(pageNum, pageSize, searchKey, catagory);
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		if (!CollectionUtils.isEmpty(tList)) {
			for (Thing thing : tList) {
				Map<String, Object> item = new HashMap<String, Object>();
				item.put("ID", thing.getId());
				item.put("USERID", thing.getUser().getId());
				item.put("USERHEADIMG", thing.getUser().getHeadimgurl());
				item.put("NICKNAME", thing.getUser().getNickName());
				item.put("TIME", DateUtils.getMyFormatTime(thing.getCreateTime()));
				item.put("LEVEL",
						WhichLevel.getLevel(thing.getUser().getHuoyueIntegral(), thing.getUser().getJiaoyiIntegral()).ordinal());
				item.put("PRICE", "￥" + thing.getCost().toString());
				item.put("OLDPRICE", thing.getOriginalCost().toString());
				List<ThingImage> thingImageList = thing.getImages();
				StringBuilder imgs = new StringBuilder();
				if (!CollectionUtils.isEmpty(thingImageList)) {
					for (ThingImage img : thingImageList) {
						imgs.append(img.getPath() + ",");
					}
					item.put("IMG", imgs.toString().substring(0, imgs.length() - 1));
				} else {
					item.put("IMG", "");
				}
				item.put("TITLE", thing.getTitle());
				item.put("DESCRIBLE", thing.getDescrible());
				long collectionNum = this.collectionThingService.getCollectionNum(thing);
				item.put("LIKE", thing.getZan());
				item.put("COMMENTNUM", collectionNum);
				resultList.add(item);
			}
			map.put("RESULTLIST", JSON.toJSONString(resultList));
			return StandardResponseBody.withPages(1, "请求成功", pageNum, false, map);
		} else {
			return StandardResponseBody.withPages(1, "请求成功", pageNum, true, map);
		}
	}

	@RequestMapping(produces = "text/plain;charset=UTF-8", value = "getComment")
	@ResponseBody
	public String getComment(HttpServletRequest request, @RequestParam("THING_ID") String thingId,
			@RequestParam("PAGEINDEX") Integer pageIndex, @RequestParam("PAGESIZE") Integer pageSize) {
		QueryResult<ThingComment> commentResult = this.commentService.getListByThingByPages(thingId, pageIndex,
				pageSize);
		List<ThingComment> commentList = commentResult.getResults();
		Map<String, Object> responseMap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (commentList != null && commentList.size() > 0) {

			for (ThingComment comment : commentList) {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				resultMap.put("HEADIMGURL", comment.getUser().getHeadimgurl());
				resultMap.put("USERID", comment.getUser().getId());
				resultMap.put("NICKNAME", comment.getUser().getNickName());
				resultMap.put("TIME", DateUtils.getMyFormatTime(comment.getCreateTime()));
				resultMap.put("CONTENT", comment.getContent());
				list.add(resultMap);
			}
		}
		responseMap.put("STATUS", "OK");
		responseMap.put("DESC", "返回成功");
		responseMap.put("RESULTLIST", JSON.toJSONString(list));
		responseMap.put("MSGNUM", this.commentService.getCommentNum(this.thingService.get(thingId)));
		return JSON.toJSONString(responseMap);
	}

	@RequestMapping(value = "addComment")
	@ResponseBody
	public String addComment(HttpServletRequest request, @RequestParam("FROM_USER") String fromUserId,
			@RequestParam("TO_USER") String toUserId, @RequestParam("THING_ID") String thingId,
			@RequestParam("CONTENT") String content) {
		Map<String, Object> responseMap = new HashMap<String, Object>();

		User from = this.userService.get(fromUserId);
		User to = this.userService.get(toUserId);
		Thing thing = this.thingService.get(thingId);
		if (from == null || to == null || thing == null) {
			responseMap.put("STATUS", "ERR");
			responseMap.put("DESC", "找不到实体类");
			return JSON.toJSONString(responseMap);
		}
		ThingComment comment = new ThingComment();
		comment.setUser(from);
		comment.setToUser(to);
		comment.setThing(thing);
		comment.setContent(content);
		if (this.commentService.addComment(comment)) {
			responseMap.put("STATUS", "OK");
			responseMap.put("DESC", "评论保存成功");
			return JSON.toJSONString(responseMap);
		} else {
			responseMap.put("STATUS", "ERR");
			responseMap.put("DESC", "评论保存异常");
			return JSON.toJSONString(responseMap);
		}
	}

	/**
	 * 收藏物品的取消和关注
	 * 
	 * @param request
	 * @param thingId
	 * @param isCollection
	 * @return
	 */
	@RequestMapping(value = "CollectionThing")
	@ResponseBody
	public String CollectionThing(HttpServletRequest request, @RequestParam("THING_ID") String thingId,
			@RequestParam("isCollection") Boolean isCollection) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		Thing thing = this.thingService.get(thingId);
		User user = (User) request.getSession().getAttribute("user");
		if (isCollection) {
			try {
				this.collectionThingService.add(thing, user);
				responseMap.put("STATUS", "OK");
				responseMap.put("DESC", "关注此闲置成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "关注此闲置失败");
			}
		} else {
			try {
				this.collectionThingService.remove(thing, user);
				responseMap.put("STATUS", "OK");
				responseMap.put("DESC", "取消关注此闲置成功");
			} catch (Exception e) {
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "取消关注此闲置失败");
			}
		}

		return JSON.toJSONString(responseMap);
	}

}
